
package com.shop.cloud.pay.admin.controller.ali;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.MultipleFactory;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.mall.common.feign.FeignShopInfoService;
import com.shop.cloud.pay.admin.config.AliPayConfiguration;
import com.shop.cloud.pay.admin.service.PayApplyFormService;
import com.shop.cloud.pay.admin.service.PayConfigService;
import com.shop.cloud.pay.common.constant.PayConstants;
import com.shop.cloud.pay.common.entity.PayApplyForm;
import com.shop.cloud.pay.common.entity.PayConfig;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里第三方应用授权
 *
 * @author
 * @date 2021-09-27 10:51:37
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/aliopenauth")
@Tag(description = "aliopenauth", name = "阿里第三方应用授权")
public class OpenAuthController {

	private final PayConfigService payConfigService;
	private final PayApplyFormService payApplyFormService;
	private final FeignShopInfoService feignShopInfoService;

	/**
	 * 支付宝授权回调处理
	 * @param response
	 * @param app_id
	 * @param app_auth_code
	 * @param state 自定义参数：店铺ID
	 * @return R
	 */
    @Operation(summary = "支付宝授权回调处理")
	@ResponseBody
    @RequestMapping("/redirect")
    public void redirect(HttpServletResponse response, String app_id, String app_auth_code, String state, String tenantId) throws Exception {
    	log.info("支付宝授权回调处理appId:"+app_id);
    	TenantContextHolder.setTenantId(tenantId);
		//设置租户ID
		PayConfig payConfig = payConfigService.findByAppId(app_id);
		TenantContextHolder.setTenantId(payConfig.getTenantId());
    	//code换token
		MultipleFactory multipleFactory = AliPayConfiguration.getFactory();
		Map<String, Object> bizParams = new HashMap<>();
		bizParams.put("grant_type", "authorization_code");
		bizParams.put("code", app_auth_code);
		AlipayOpenApiGenericResponse oauthTokenResponse = multipleFactory.Generic().execute("alipay.open.auth.token.app",null, bizParams);
		String alertStr;
		Boolean alertImg;
		if(PayConstants.ALI_RES_CODE_SUCCESS.equals(oauthTokenResponse.getCode())){
			String body = oauthTokenResponse.getHttpBody();
			JSONObject bodyJSONObject = JSONUtil.parseObj(body);
			JSONObject responseJSONObject = bodyJSONObject.getJSONObject("alipay_open_auth_token_app_response");
			String code = responseJSONObject.getStr("code");
			if(PayConstants.ALI_RES_CODE_SUCCESS.equals(code)){
				String aliAuthToken = responseJSONObject.getStr("app_auth_token");
				//保证app_auth_token到支付进件申请单
				PayApplyForm payApplyForm = new PayApplyForm();
				payApplyForm.setPayType(PayConstants.PAY_TYPE_2);
				payApplyForm.setSubMchid(aliAuthToken);
				payApplyForm.setShopId(state);
				payApplyForm.setApplymentId(responseJSONObject.getStr("user_id"));
				Boolean rs = payApplyFormService.save(payApplyForm);
				//更新店铺AliAuthToken
//				feignShopInfoService.updateAliAuthTokenInside(state, aliAuthToken, SecurityConstants.FROM_IN);
				if(rs){
					alertImg = true;
					alertStr = "<div style='text-align: center;font-size: 35px;color: green'>恭喜您！授权成功</div>";
				}else{
					alertImg = false;
					alertStr = "<div style='text-align: center;font-size: 35px;color: red'>授权失败，请联系管理员</div>";
				}
			}else{
				alertImg = false;
				alertStr = "<div style='text-align: center;font-size: 35px;color: red'>授权失败，请联系管理员："+responseJSONObject.getStr("msg")+"</div>";
			}
		}else{
			alertImg = false;
			alertStr = "<div style='text-align: center;font-size: 35px;color: red'>授权失败，请联系管理员："+oauthTokenResponse.getMsg()+"："+oauthTokenResponse.getSubMsg()+"</div>";
		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter os =response.getWriter();
		os.print("<html>");
		os.print("<head>");
		os.print("<title>");
		os.print("授权结果");
		os.print("</title>");
		os.print("</head>");
		os.print("<body>");
		if(alertImg){
			os.print("<div style='text-align: center;font-size: 35px;color: green'><img style='width:200px;higth:200px' src=''></div>");
		}
		os.print(alertStr);
		os.print("</body>");
		os.print("</html>");
    }


}
